<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>贪吃蛇游戏</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#22c55e', // 蛇身主色-绿色
            secondary: '#ef4444', // 食物颜色-红色
            accent: '#f59e0b', // 强调色-黄色
            dark: '#1e293b', // 深色背景
            light: '#f8fafc' // 浅色文本
          },
          fontFamily: {
            game: ['"Press Start 2P"', 'cursive', 'sans-serif']
          }
        }
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .text-shadow {
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
      }
      .pixel-corners {
        clip-path: polygon(
          0% 5px, 5px 5px, 5px 0%, calc(100% - 5px) 0%, calc(100% - 5px) 5px,
          100% 5px, 100% calc(100% - 5px), calc(100% - 5px) calc(100% - 5px),
          calc(100% - 5px) 100%, 5px 100%, 5px calc(100% - 5px), 0% calc(100% - 5px)
        );
      }
    }
  </style>

  <style>
    /* 游戏核心样式 */
    #gameCanvas {
      display: block;
      background-color: #0f172a;
      border: 2px solid #22c55e;
      transition: all 0.3s ease;
    }

    #gameCanvas:hover {
      box-shadow: 0 0 15px rgba(34, 197, 94, 0.5);
    }

    /* 控制按钮动画 */
    .control-btn {
      transition: all 0.15s ease;
    }

    .control-btn:active {
      transform: scale(0.9);
    }

    /* 蛇移动动画 */
    @keyframes pulse {
      0%, 100% { transform: scale(1); }
      50% { transform: scale(1.05); }
    }

    .food-pulse {
      animation: pulse 1.5s infinite;
    }

    /* 渐变背景 */
    .gradient-bg {
      background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
    }
  </style>
</head>
<body class="gradient-bg min-h-screen text-light flex flex-col items-center justify-center p-4 font-sans">
  <!-- 游戏容器 -->
  <div class="max-w-4xl w-full mx-auto flex flex-col lg:flex-row gap-6 items-center lg:items-start justify-center">

    <!-- 游戏信息面板 -->
    <div class="w-full lg:w-64 flex flex-col gap-4">
      <div class="bg-dark/80 backdrop-blur-sm p-4 rounded-lg border border-primary/30">
        <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-primary text-center mb-2 text-shadow">贪吃蛇</h1>
        <p class="text-sm text-gray-300 text-center mb-4">使用方向键或屏幕按钮控制</p>

        <!-- 分数显示 -->
        <div class="space-y-3">
          <div class="flex justify-between items-center">
            <span class="text-gray-300">当前分数:</span>
            <span id="score" class="text-accent font-bold">0</span>
          </div>
          <div class="flex justify-between items-center">
            <span class="text-gray-300">最高分:</span>
            <span id="highScore" class="text-primary font-bold">0</span>
          </div>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="bg-dark/80 backdrop-blur-sm p-4 rounded-lg border border-primary/30">
        <h2 class="text-center text-lg font-semibold mb-3">控制</h2>
        <div class="grid grid-cols-3 gap-2">
          <div class="col-start-2">
            <button id="up" class="control-btn w-full bg-primary/20 hover:bg-primary/30 text-primary p-3 rounded-lg">
              <i class="fa fa-arrow-up"></i>
            </button>
          </div>
          <div class="col-start-1 row-start-2">
            <button id="left" class="control-btn w-full bg-primary/20 hover:bg-primary/30 text-primary p-3 rounded-lg">
              <i class="fa fa-arrow-left"></i>
            </button>
          </div>
          <div class="col-start-2 row-start-2">
            <button id="startPause" class="control-btn w-full bg-accent/20 hover:bg-accent/30 text-accent p-3 rounded-lg">
              <i class="fa fa-play"></i> 开始
            </button>
          </div>
          <div class="col-start-3 row-start-2">
            <button id="right" class="control-btn w-full bg-primary/20 hover:bg-primary/30 text-primary p-3 rounded-lg">
              <i class="fa fa-arrow-right"></i>
            </button>
          </div>
          <div class="col-start-2 row-start-3">
            <button id="down" class="control-btn w-full bg-primary/20 hover:bg-primary/30 text-primary p-3 rounded-lg">
              <i class="fa fa-arrow-down"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 难度选择 -->
      <div class="bg-dark/80 backdrop-blur-sm p-4 rounded-lg border border-primary/30">
        <h2 class="text-center text-lg font-semibold mb-3">难度</h2>
        <div class="flex gap-2">
          <button class="difficulty-btn flex-1 bg-gray-700 hover:bg-gray-600 p-2 rounded" data-speed="150">简单</button>
          <button class="difficulty-btn flex-1 bg-primary/20 hover:bg-primary/30 text-primary p-2 rounded" data-speed="100">中等</button>
          <button class="difficulty-btn flex-1 bg-gray-700 hover:bg-gray-600 p-2 rounded" data-speed="60">困难</button>
        </div>
      </div>
    </div>

    <!-- 游戏画布区域 -->
    <div class="relative">
      <canvas id="gameCanvas" class="pixel-corners"></canvas>

      <!-- 游戏开始遮罩 -->
      <div id="startScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center gap-4">
        <h2 class="text-2xl font-bold text-primary">贪吃蛇游戏</h2>
        <p class="text-center px-4">吃掉红色食物得分，但不要撞到墙壁或自己的身体</p>
        <button id="startBtn" class="bg-primary hover:bg-primary/80 text-white font-bold py-2 px-6 rounded-lg transition-all transform hover:scale-105">
          开始游戏
        </button>
      </div>

      <!-- 游戏结束遮罩 -->
      <div id="gameOverScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center gap-4 hidden">
        <h2 class="text-2xl font-bold text-secondary">游戏结束!</h2>
        <p>你的得分: <span id="finalScore" class="text-accent font-bold">0</span></p>
        <button id="restartBtn" class="bg-primary hover:bg-primary/80 text-white font-bold py-2 px-6 rounded-lg transition-all transform hover:scale-105">
          再来一局
        </button>
      </div>

      <!-- 暂停遮罩 -->
      <div id="pauseScreen" class="absolute inset-0 bg-dark/80 backdrop-blur-sm flex flex-col items-center justify-center gap-4 hidden">
        <h2 class="text-2xl font-bold text-accent">游戏暂停</h2>
        <button id="resumeBtn" class="bg-primary hover:bg-primary/80 text-white font-bold py-2 px-6 rounded-lg transition-all transform hover:scale-105">
          继续游戏
        </button>
      </div>
    </div>
  </div>

  <!-- 移动设备控制区 (仅在小屏幕显示) -->
  <div class="lg:hidden mt-6 w-full max-w-xs">
    <div class="grid grid-cols-3 gap-2">
      <div class="col-start-2">
        <button id="mobileUp" class="control-btn w-full h-16 bg-primary/20 hover:bg-primary/30 text-primary rounded-lg text-2xl">
          <i class="fa fa-arrow-up"></i>
        </button>
      </div>
      <div class="col-start-1 row-start-2">
        <button id="mobileLeft" class="control-btn w-full h-16 bg-primary/20 hover:bg-primary/30 text-primary rounded-lg text-2xl">
          <i class="fa fa-arrow-left"></i>
        </button>
      </div>
      <div class="col-start-2 row-start-2">
        <button id="mobileDown" class="control-btn w-full h-16 bg-primary/20 hover:bg-primary/30 text-primary rounded-lg text-2xl">
          <i class="fa fa-arrow-down"></i>
        </button>
      </div>
      <div class="col-start-3 row-start-2">
        <button id="mobileRight" class="control-btn w-full h-16 bg-primary/20 hover:bg-primary/30 text-primary rounded-lg text-2xl">
          <i class="fa fa-arrow-right"></i>
        </button>
      </div>
    </div>
  </div>

  <script>
    // 游戏常量和变量
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');

    // 设置画布尺寸 (响应式)
    function resizeCanvas() {
      const containerWidth = window.innerWidth < 768 ? window.innerWidth - 40 : 600;
      const size = Math.min(containerWidth, 600);
      canvas.width = size;
      canvas.height = size;
    }

    // 初始化时调整一次大小
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    // 游戏参数
    let gridSize; // 网格大小，根据画布尺寸动态计算
    let snake = []; // 蛇的身体
    let food = {}; // 食物位置
    let direction = ''; // 当前方向
    let nextDirection = ''; // 下一个方向
    let score = 0;
    let highScore = localStorage.getItem('snakeHighScore') || 0;
    let gameSpeed = 100; // 游戏速度，毫秒
    let gameLoop; // 游戏循环
    let isGameRunning = false; // 游戏是否运行
    let isGameOver = false; // 游戏是否结束

    // DOM 元素
    const scoreElement = document.getElementById('score');
    const highScoreElement = document.getElementById('highScore');
    const startPauseButton = document.getElementById('startPause');
    const startScreen = document.getElementById('startScreen');
    const gameOverScreen = document.getElementById('gameOverScreen');
    const pauseScreen = document.getElementById('pauseScreen');
    const finalScoreElement = document.getElementById('finalScore');

    // 更新高分显示
    highScoreElement.textContent = highScore;

    // 初始化游戏
    function initGame() {
      // 计算网格大小 (确保是偶数，以便蛇和食物对齐)
      gridSize = Math.floor(canvas.width / 20);
      if (gridSize % 2 !== 0) gridSize--;

      // 初始化蛇的位置 (居中)
      const center = Math.floor(canvas.width / (2 * gridSize)) * gridSize;
      snake = [
        { x: center, y: center },
        { x: center - gridSize, y: center },
        { x: center - gridSize * 2, y: center }
      ];

      // 初始方向向右
      direction = 'right';
      nextDirection = 'right';

      // 生成初始食物
      generateFood();

      // 重置分数
      score = 0;
      scoreElement.textContent = score;

      // 重置游戏状态
      isGameRunning = false;
      isGameOver = false;

      // 隐藏所有屏幕
      gameOverScreen.classList.add('hidden');
      pauseScreen.classList.add('hidden');
      startScreen.classList.remove('hidden');

      // 更新按钮文本
      startPauseButton.innerHTML = '<i class="fa fa-play"></i> 开始';

      // 绘制初始状态
      draw();
    }

    // 生成食物
    function generateFood() {
      // 随机位置，但要与网格对齐
      const maxPos = canvas.width - gridSize;
      food = {
        x: Math.floor(Math.random() * (maxPos / gridSize)) * gridSize,
        y: Math.floor(Math.random() * (maxPos / gridSize)) * gridSize
      };

      // 确保食物不会出现在蛇身上
      const isOnSnake = snake.some(segment => segment.x === food.x && segment.y === food.y);
      if (isOnSnake) {
        generateFood();
      }
    }

    // 绘制游戏
    function draw() {
      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // 绘制蛇
      snake.forEach((segment, index) => {
        // 蛇头颜色深一点
        ctx.fillStyle = index === 0 ? '#16a34a' : '#22c55e';

        // 绘制蛇身体
        ctx.fillRect(segment.x, segment.y, gridSize, gridSize);

        // 绘制蛇身体边框
        ctx.strokeStyle = '#1e293b';
        ctx.lineWidth = 2;
        ctx.strokeRect(segment.x, segment.y, gridSize, gridSize);
      });

      // 绘制食物
      ctx.fillStyle = '#ef4444';
      ctx.beginPath();
      ctx.arc(
        food.x + gridSize / 2,
        food.y + gridSize / 2,
        gridSize / 2 - 2,
        0,
        Math.PI * 2
      );
      ctx.fill();

      // 食物发光效果
      ctx.shadowColor = '#ef4444';
      ctx.shadowBlur = 10;
      ctx.fill();
      ctx.shadowBlur = 0; // 重置阴影
    }

    // 更新游戏状态
    function update() {
      // 更新方向
      direction = nextDirection;

      // 获取蛇头位置
      const head = { x: snake[0].x, y: snake[0].y };

      // 根据方向移动蛇头
      switch(direction) {
        case 'up':
          head.y -= gridSize;
          break;
        case 'down':
          head.y += gridSize;
          break;
        case 'left':
          head.x -= gridSize;
          break;
        case 'right':
          head.x += gridSize;
          break;
      }

      // 检查碰撞
      // 墙壁碰撞
      if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
        gameOver();
        return;
      }

      // 自身碰撞
      if (snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        gameOver();
        return;
      }

      // 将新头部添加到蛇
      snake.unshift(head);

      // 检查是否吃到食物
      if (head.x === food.x && head.y === food.y) {
        // 加分
        score += 10;
        scoreElement.textContent = score;

        // 更新最高分
        if (score > highScore) {
          highScore = score;
          highScoreElement.textContent = highScore;
          localStorage.setItem('snakeHighScore', highScore);
        }

        // 生成新食物
        generateFood();
      } else {
        // 如果没吃到食物，移除尾部
        snake.pop();
      }

      // 绘制更新后的游戏状态
      draw();
    }

    // 游戏循环
    function startGameLoop() {
      if (gameLoop) clearInterval(gameLoop);
      gameLoop = setInterval(update, gameSpeed);
    }

    // 开始/暂停游戏
    function toggleGame() {
      if (isGameOver) {
        // 如果游戏结束，重新开始
        initGame();
        return;
      }

      if (isGameRunning) {
        // 暂停游戏
        clearInterval(gameLoop);
        pauseScreen.classList.remove('hidden');
        startPauseButton.innerHTML = '<i class="fa fa-play"></i> 继续';
      } else {
        // 开始/继续游戏
        startGameLoop();
        startScreen.classList.add('hidden');
        pauseScreen.classList.add('hidden');
        startPauseButton.innerHTML = '<i class="fa fa-pause"></i> 暂停';
      }

      isGameRunning = !isGameRunning;
    }

    // 游戏结束
    function gameOver() {
      clearInterval(gameLoop);
      isGameRunning = false;
      isGameOver = true;

      // 显示游戏结束屏幕
      finalScoreElement.textContent = score;
      gameOverScreen.classList.remove('hidden');

      // 更新按钮文本
      startPauseButton.innerHTML = '<i class="fa fa-refresh"></i> 重启';
    }

    // 改变方向
    function changeDirection(newDirection) {
      // 防止180度转向
      if (
        (newDirection === 'up' && direction === 'down') ||
        (newDirection === 'down' && direction === 'up') ||
        (newDirection === 'left' && direction === 'right') ||
        (newDirection === 'right' && direction === 'left')
      ) {
        return;
      }

      nextDirection = newDirection;
    }

    // 设置难度
    function setDifficulty(speed) {
      gameSpeed = speed;

      // 更新按钮样式
      document.querySelectorAll('.difficulty-btn').forEach(btn => {
        if (parseInt(btn.dataset.speed) === speed) {
          btn.classList.add('bg-primary/20', 'hover:bg-primary/30', 'text-primary');
          btn.classList.remove('bg-gray-700', 'hover:bg-gray-600');
        } else {
          btn.classList.remove('bg-primary/20', 'hover:bg-primary/30', 'text-primary');
          btn.classList.add('bg-gray-700', 'hover:bg-gray-600');
        }
      });

      // 如果游戏正在运行，重新启动游戏循环以应用新速度
      if (isGameRunning) {
        startGameLoop();
      }
    }

    // 事件监听 - 键盘控制
    document.addEventListener('keydown', (e) => {
      switch(e.key) {
        case 'ArrowUp':
          changeDirection('up');
          break;
        case 'ArrowDown':
          changeDirection('down');
          break;
        case 'ArrowLeft':
          changeDirection('left');
          break;
        case 'ArrowRight':
          changeDirection('right');
          break;
        case ' ': // 空格键控制开始/暂停
          e.preventDefault();
          toggleGame();
          break;
      }
    });

    // 事件监听 - 按钮控制
    document.getElementById('up').addEventListener('click', () => changeDirection('up'));
    document.getElementById('down').addEventListener('click', () => changeDirection('down'));
    document.getElementById('left').addEventListener('click', () => changeDirection('left'));
    document.getElementById('right').addEventListener('click', () => changeDirection('right'));
    document.getElementById('startPause').addEventListener('click', toggleGame);
    document.getElementById('startBtn').addEventListener('click', toggleGame);
    document.getElementById('restartBtn').addEventListener('click', initGame);
    document.getElementById('resumeBtn').addEventListener('click', toggleGame);

    // 移动设备控制
    document.getElementById('mobileUp').addEventListener('click', () => changeDirection('up'));
    document.getElementById('mobileDown').addEventListener('click', () => changeDirection('down'));
    document.getElementById('mobileLeft').addEventListener('click', () => changeDirection('left'));
    document.getElementById('mobileRight').addEventListener('click', () => changeDirection('right'));

    // 难度按钮
    document.querySelectorAll('.difficulty-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        setDifficulty(parseInt(btn.dataset.speed));
      });
    });

    // 触摸滑动控制 (移动设备)
    let touchStartX = 0;
    let touchStartY = 0;

    canvas.addEventListener('touchstart', (e) => {
      touchStartX = e.touches[0].clientX;
      touchStartY = e.touches[0].clientY;
      e.preventDefault(); // 防止滚动
    }, { passive: false });

    canvas.addEventListener('touchmove', (e) => {
      e.preventDefault(); // 防止滚动
    }, { passive: false });

    canvas.addEventListener('touchend', (e) => {
      if (!isGameRunning) return;

      const touchEndX = e.changedTouches[0].clientX;
      const touchEndY = e.changedTouches[0].clientY;

      const diffX = touchEndX - touchStartX;
      const diffY = touchEndY - touchStartY;

      // 确定滑动方向 (水平还是垂直滑动)
      if (Math.abs(diffX) > Math.abs(diffY)) {
        // 水平滑动
        if (diffX > 0) {
          changeDirection('right');
        } else {
          changeDirection('left');
        }
      } else {
        // 垂直滑动
        if (diffY > 0) {
          changeDirection('down');
        } else {
          changeDirection('up');
        }
      }

      e.preventDefault(); // 防止滚动
    }, { passive: false });

    // 初始化游戏
    initGame();
  </script>
</body>
</html>